import mediaLibrary from '@ohos.multimedia.mediaLibrary'
import DateTimeUtil from '../model/DateTimeUtil'
import Logger from './Logger'

export default class MediaUtils {
  private tag: string = 'zyk MediaUtils'
  private mediaTest: mediaLibrary.MediaLibrary = mediaLibrary.getMediaLibrary(globalThis.abilityContext)
  private static instance: MediaUtils = new MediaUtils()

  public static getInstance() {
    if (this.instance === undefined) {
      this.instance = new MediaUtils()
    }
    return this.instance
  }

  async createAndGetUri(mediaType: number) {
    let info = this.getInfoFromType(mediaType)
    let dateTimeUtil = new DateTimeUtil()
    let name = `${dateTimeUtil.getDate()}_${dateTimeUtil.getTime()}`
    let displayName = `${info.prefix}${name}${info.suffix}`
    Logger.info(this.tag, `displayName = ${displayName},mediaType = ${mediaType}`)
    let publicPath = await this.mediaTest.getPublicDirectory(info.directory)
    Logger.info(this.tag, `publicPath = ${publicPath}`)
    try {
      return await this.mediaTest.createAsset(mediaType, displayName, publicPath)
    } catch (err) {
      Logger.info(this.tag, `createAsset err ` + JSON.stringify(err))
    }

  }

  async getFdPath(fileAsset: any) {
    let fd = await fileAsset.open('Rw')
    Logger.info(this.tag, `fd = ${fd}`)
    return fd
  }

  onChangePhotoFormat() {
    if (globalThis.settingDataObj.photoFormat == 0) {
      return 'png'
    }
    if (globalThis.settingDataObj.photoFormat == 1) {
      return 'jpg'
    }
    if (globalThis.settingDataObj.photoFormat == 2) {
      return 'bmp'
    }
    if (globalThis.settingDataObj.photoFormat == 3) {
      return 'webp'
    }
    if (globalThis.settingDataObj.photoFormat == 4) {
      return 'jpeg'
    }
  }

  getInfoFromType(mediaType: number) {
    let result = {
      prefix: '', suffix: '', directory: 0
    }
    switch (mediaType) {
      case mediaLibrary.MediaType.IMAGE:
        result.prefix = 'IMG_'
        // result.suffix = '.jpg'
        result.suffix = `.${this.onChangePhotoFormat()}`
        result.directory = mediaLibrary.DirectoryType.DIR_CAMERA
        break
      case mediaLibrary.MediaType.VIDEO:
        result.prefix = 'VID_'
        result.suffix = '.mp4'
        result.directory = mediaLibrary.DirectoryType.DIR_CAMERA
        break
    }
    return result
  }
}